//
//  PersonInfoViewController.m
//  mhome
//
//  Created by 刘春雷 on 2018/12/5.
//  Copyright © 2018年 刘春雷. All rights reserved.
//

#import "PersonInfoViewController.h"
#import "ZYQAssetPickerController.h"
#import "NetworkManager.h"
#import "DataManager.h"
#import "PersonModel.h"
#import "AppDelegate.h"

@interface PersonInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ZYQAssetPickerControllerDelegate>
@property (nonatomic,copy) NSArray *titleArray;
@property (nonatomic,strong) NSMutableArray *contentArray;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIActionSheet * actionSheet;
@property (nonatomic,strong) UIImage *infoImage;
@property (nonatomic, copy) NSArray *dataSourceArray;
@property (nonatomic,copy)  NSString *touxiang;
@end

@implementation PersonInfoViewController
- (NSMutableArray *)contentArray {
    if(!_contentArray) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self doNetworking];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
    self.title = @"个人信息";
    self.titleArray = @[@"头像",@"昵称",@"性别",@"手机号码",@"邮箱",@"所在城市",@"装修风格偏好"];
//    UIButton *button = [[UIButton alloc]initWithFrame:CGRects(0, 30, 70, 14)];
    //右边按钮
//    [button addTarget:self action:@selector(backs) forControlEvents:UIControlEventTouchUpInside];
//    [button setTitle:@"编辑" forState:UIControlStateNormal];
//    button.titleLabel.font=[UIFont systemFontOfSize:16.0];
//    [button setTitleColor:[UIColor colorWithRed:123.0/255.0 green:131.0/255.0 blue:141.0/255.0 alpha:1.0] forState:UIControlStateNormal];
//    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:button];
//    self.navigationItem.rightBarButtonItem = item1;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRects(0, 0, 375 , 480) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    UIButton *exitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    exitButton.frame = CGRects(15, 496, 345, 53);
    exitButton.backgroundColor = [UIColor whiteColor];
    [exitButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [exitButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    exitButton.layer.masksToBounds = YES;
    exitButton.layer.cornerRadius = 8;
    [exitButton addTarget:self action:@selector(exitEvent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exitButton];
}
- (void)doNetworking {
    NSString *urlString = [NSString stringWithFormat:@"%@%@",Domain,@"ucenter/getUserInfoByUserId"];
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = @{@"id":[de stringForKey:@"userid"]};
    [[NetworkManager manager] sendPostRequestWithUrl:urlString paramenters:dic success:^(id responseObject) {
        NSLog(@"成功%@",responseObject);
        if([responseObject[@"code"]  isEqual: @1]){
            self.dataSourceArray = [DataManager getPersonInfoData:responseObject];
            NSLog(@"======%@",self.dataSourceArray);
            [self dealWithData];
        }else{
            [QMUITips showInfo:responseObject[@"msg"] inView:self.view hideAfterDelay:1];
        }
    } failure:^(NSError *error) {
        NSLog(@"失败%@",error);
    }];
}
- (void)dealWithData {
    PersonModel *model = self.dataSourceArray[0];
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    [self.contentArray addObject:[de objectForKey:@"launcherHeadurl"]?[de objectForKey:@"launcherHeadurl"]:@"头像"];
 
    [self.contentArray addObject:[model.nickName isEqualToString:@" "]?model.nickName:@"暂无"];
    if([self.model.gender isEqualToString:@"0"]){
         [self.contentArray addObject:@"保密"];
    }else if ([self.model.gender isEqualToString:@"1"]){
        [self.contentArray addObject:@"男"];
    }else{
        [self.contentArray addObject:@"女"];
    }
    [self.contentArray addObject:model.mobile];
    [self.contentArray addObject:[model.email isEqualToString:@" "]?model.email:@"暂无"];
    [self.contentArray addObject:[model.city isEqualToString:@" "]?self.model.city:@"暂无"];
    [self.contentArray addObject:[model.styleLikeName isEqualToString:@" "]?model.styleLikeName:@"暂无"];
    [self.tableView reloadData];
    
}
- (void)exitEvent {
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    [de setBool:NO forKey:@"login"];
    [de setObject:nil forKey:@"username"];
    [de synchronize];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@appserve/comment/cancelMsgDeviceBind", Domain];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic =@{@"userId": [userDefaults valueForKey:@"userid"]};
    [[NetworkManager manager] sendPostRequestWithUrl:urlStr paramenters:dic success:^(id responseObject) {
        QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(QMUIAlertAction *action) {
        }];
        QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定" style:QMUIAlertActionStyleDestructive handler:^(QMUIAlertAction *action) {
            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [delegate enterTabBarController];
        }];
        QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"提示" message:@"是否退出登录" preferredStyle:QMUIAlertControllerStyleAlert];
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController showWithAnimated:YES];
                                                                          } failure:^(NSError *error) {
                                                                          }];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArray.count;
}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 86*BIZ;
    }else{
        return 50*BIZ;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = self.titleArray[indexPath.row];
    if(self.contentArray.count > 0){
        if (indexPath.row == 0) {
            UIImageView *image = [[UIImageView alloc]init];
            image.frame = CGRects(306, 18, 46, 46);
            [image sd_setImageWithURL:self.contentArray[indexPath.row]placeholderImage:[UIImage imageNamed:@"头像"] options:SDWebImageRetryFailed];
            [image.layer setMasksToBounds:YES];//设置按钮的圆角半径不会被遮挡
            [image.layer setCornerRadius:23.0*BIZ];//设置边界圆角
            [cell  addSubview:image];
        }else{
            cell.detailTextLabel.text = self.contentArray[indexPath.row];
        }
    }
    return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0&&indexPath.section == 0) {
        UIAlertView * Alert=[[UIAlertView alloc]initWithTitle:@"请选择获取方式" message:@""
                                                     delegate:self cancelButtonTitle:@"取消" otherButtonTitles:
                             @"打开照相机",@"从手机相册获取", nil];
        Alert.delegate=self;
        [Alert show ];
    }
    
}
//UIAlertView的代理方法
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [self getAvatatFormCamera:self];//调用相机
    }
    if (buttonIndex ==2) {
        [self getAvatatFormPhotoLibrary:self];//调用相册
    }
}

# pragma mark -- 调用相册
- (void)getAvatatFormPhotoLibrary:(UIViewController *)controller{
    //这里可以判断类型是相册还是相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        //加上下面这句会有编辑框
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

# pragma mark -- 调用相机
- (void)getAvatatFormCamera:(UIViewController *)controller{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    picker.showsCameraControls = YES;
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    self.infoImage = [info objectForKey:UIImagePickerControllerEditedImage];
    NSString *urlString = [NSString stringWithFormat:@"%@appserve/common/uploadImage",Domain];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    [manager POST:urlString parameters:@{@"type":@"1",@"userId":[de stringForKey:@"userid"],@"appkey":[de stringForKey:@"appkey"]}constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImageJPEGRepresentation(self.infoImage, 1);
        NSLog(@"--------%@",data);
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
        [formData appendPartWithFileData:data name:@"iconImg" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"-------%@",dic);
        self.touxiang = dic[@"data"];
        NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
        [de setObject:[NSString stringWithFormat:@"%@%@",@"http://img.mhome.com/",self.touxiang ]forKey:@"launcherHeadurl"];
        [de synchronize];
        [self upPhone];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
-(void) upPhone
{
    NSString *urlString = [NSString stringWithFormat:@"%@ucenter/updateUserInfo",Domain];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = @{@"headUrl":self.touxiang,@"id":[de stringForKey:@"userid"]};
    NSLog(@"======%@",dic);
    [manager POST:urlString parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"-------%@",dic);
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
        [self.contentArray replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:@"http://img.mhome.com/%@",self.touxiang]];
        [self.tableView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
